package proto_wearebatman;

import java.util.LinkedList;

public class Wire implements Ioperable {

    private int inPin, outPin;
    private IhasInput in;
    private IhasOutput out;
    private String name;
    private LinkedList<Wire> wires;

    public Wire(String name) {
        this.name = name;
        this.wires = new LinkedList<Wire>();

        // Proto Output
        Main.println("Wire created: " + this.name);
    }

    public void connect(IhasOutput out, int outIndex, IhasInput in, int inIndex) {
        // Logic
        this.inPin = inIndex;
        this.outPin = outIndex;
        this.in = in;
        this.out = out;
        out.connectWireOutput(inIndex, this);
        in.connectWireInput(outIndex, this);

        // Proto Output
        Main.println(out.getName() + " connected to " + this.getName());
        Main.println(this.getName() + " connected to " + in.getName());
    }

    public void connect(Wire wire, IhasInput in, int inIndex) {
        this.inPin = inIndex;
        this.outPin = wire.outPin;
        this.in = in;
        this.out = wire.out;
        in.connectWireInput(inIndex, this);

        wire.addWire(this);

        // Proto Output
        Main.println(wire.getName() + " connected to " + this.getName());
        Main.println(this.getName() + " connected to " + in.getName());
    }

    public void addWire(Wire w) {
        this.wires.add(w);
    }

    public void operate() {
        in.setInputData(inPin, out.getOutputData(outPin));
        //Main.println(this.name + ".operate() | Data = " + this.in.getInputData(outPin));
        in.operate();
        if (!this.wires.isEmpty()) {
            for (int i = 0; i < this.wires.size(); i++) {
                this.wires.get(i).operate();
            }
        }        
    }

    public String getName() {
        return this.name;
    }

    public void resetCounter() {

    }

    public String getFinalState() {
        return Integer.toString(this.in.getInputData(0));
    }
}
